package web

import (
	"a-admin/web/middleware"
	"a-admin/web/router/app"
	"a-admin/web/router/demo"
	"a-admin/web/router/rtc"
	"a-admin/web/router/system"
	"a-common/config"
	"a-common/myerr"
	"fmt"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/fiber/v2/middleware/recover"
)

func Start() {
	conf := config.Config

	appf := fiber.New(fiber.Config{
		// Prefork:       true, // 多线程
		CaseSensitive: true,
		StrictRouting: true,
		ServerHeader:  conf.App.Introduction,
		AppName:       conf.App.Name,
	})
	// ! 接口限流，请请勿在访问频繁的接口上设置,暂时注释该配置
	// app.Use(limiter.New())
	// 是否打印请求日志
	appf.Use(logger.New())
	// CORS for external resources
	appf.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowHeaders: "Cache-Control",
		// AllowCredentials: true,
	}))
	// 认证
	appf.Use(middleware.AuthHandler())

	// 统一异常处理
	appf.Use(middleware.ErrorHandler())

	// 故障恢复
	appf.Use(recover.New())

	baseRoute := appf.Group("/dev")
	// 注册路由信息
	initRoutes(baseRoute)

	// Last middleware to match anything
	appf.Use(func(c *fiber.Ctx) error {
		return myerr.ERR_SYS_404
	})
	err := appf.Listen(conf.Server.Port)
	if err != nil {
		fmt.Println("Error starting server:", err.Error())
		return
	}
}

// 初始化路由
func initRoutes(r fiber.Router) {
	// 系统服务
	system.InitSystemRoutes(r)
	// 即时通讯
	rtc.InitRtcRoutes(r)
	// APP 移动端接口
	app.InitAppRoutes(r)

	// demo 房屋管理
	demo.InitdemoRoutes(r)
}
